package cn.itsource.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import cn.itsource.bean.Employee;
import cn.itsource.bean.PetType;
import cn.itsource.bean.SearchMasterMsg;
import cn.itsource.bean.Shop;
import cn.itsource.config.PageList;
import cn.itsource.mapper.SearchMasterMsgMapper;
import cn.itsource.query.SearchMsgQuery;
import cn.itsource.service.*;
import cn.itsource.util.JsonResult;
import cn.itsource.util.baidu.DistanceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static cn.itsource.util.PetHomeConstant.SEARCH_MSG.SEARCH_MSG_PASS;
import static cn.itsource.util.PetHomeConstant.SEARCH_MSG.SEARCH_MSG_PENDING;
import static cn.itsource.util.PetHomeConstant.SYSTEM_LOGIN_ERROR;
import static cn.itsource.util.RedisContants.LOGIN_USER_KEY;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-21 11:27:00
 */
@Service
public class SearchMasterMsgServiceImpl extends ServiceImpl<SearchMasterMsgMapper, SearchMasterMsg> implements ISearchMasterMsgService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IPetTypeService petTypeService;

    @Resource
    private IShopService shopService;

    @Resource
    private IOrderPetAcquisitionService orderPetAcquisitionService;


    @Resource
    private ISearchMasterLogService searchMasterLogService;


    @Override
    public JsonResult getPage(SearchMsgQuery query,HttpServletRequest request) {
//        Page<SearchMasterMsg> page = new Page<>();


        //添加筛选条件，当距离超过5000m时不能展示
        String token = request.getHeader("token");
        String key = LOGIN_USER_KEY + token;
        //查询数据
        String empMsg = stringRedisTemplate.opsForValue().get(key);
        //信息不能为空
        if (StringUtils.isEmpty(empMsg)){
            return JsonResult.error("账号信息异常，请重新登入",SYSTEM_LOGIN_ERROR);
        }
        //转成java对象
        Employee employee = JSONUtil.toBean(empMsg, Employee.class);
        Long employeeId = employee.getId();
        Long shopId = employee.getShopId();
        //shopid不能为空
        if (shopId==null){
            return JsonResult.error("账号信息异常，请联系管理员",SYSTEM_LOGIN_ERROR);
        }

        //通过shopid查询店铺信息
        Shop shop = shopService.getById(shopId);
        if (shop==null){
            return JsonResult.error("店铺信息异常，请联系管理员",SYSTEM_LOGIN_ERROR);
        }
        LambdaQueryWrapper<SearchMasterMsg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Strings.isEmpty(query.getState()),SearchMasterMsg::getState,SEARCH_MSG_PENDING);
        queryWrapper.eq(Strings.isNotEmpty(query.getState()),SearchMasterMsg::getState,query.getState());
        queryWrapper.eq(Strings.isNotEmpty(query.getState()),SearchMasterMsg::getShopId,shopId);
        queryWrapper.like(Strings.isNotEmpty(query.getKeyword()),SearchMasterMsg::getName,query.getKeyword())
                .or().like(StringUtils.isNotEmpty(query.getKeyword()),SearchMasterMsg::getTitle,query.getKeyword())
                .or().like(Strings.isNotEmpty(query.getKeyword()),SearchMasterMsg::getAddress,query.getKeyword())
                .or().eq(SearchMasterMsg::getShopId,null);

        String shopAddress = shop.getAddress();


        List<SearchMasterMsg> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)){
            return JsonResult.success("暂无数据");
        }



        list = list.stream().map(item -> {
            Long petType = item.getPetType();
            if (petType != null) {
                PetType byId = petTypeService.getById(petType);
                String name = byId.getName();
                item.setPetTypeName(name);
            }
            item.setGenderName(item.getGender()?"绅士":"淑女");
            return item;
        }).collect(Collectors.toList());

        List<SearchMasterMsg> collect = list.stream().filter(item -> DistanceUtil.isInCircle(item.getAddress(), shopAddress,5000)).collect(Collectors.toList());

        //stream流手动分页
        collect = collect.stream().skip(query.getRows()*(query.getPage()-1)).limit(query.getRows()).collect(Collectors.toList());

        Long total = Long.valueOf(collect.size());

        PageList<SearchMasterMsg> pageList = new PageList<>();
        pageList.setTotal(total);
        pageList.setList(collect);

        return JsonResult.success(pageList);
    }

    @Override
    @Transactional
    public JsonResult access(SearchMasterMsg msg, HttpServletRequest request) {
        //获取到接单请求后，再次验证店铺距离是否<5000米
        String address = msg.getAddress();

        //添加筛选条件，当距离超过5000m时不能下订单
        String token = request.getHeader("token");
        String key = LOGIN_USER_KEY + token;
        //查询数据
        String empMsg = stringRedisTemplate.opsForValue().get(key);
        //信息不能为空
        if (StringUtils.isEmpty(empMsg)){
            return JsonResult.error("账号信息异常，请重新登入",SYSTEM_LOGIN_ERROR);
        }
        //转成java对象
        Employee employee = JSONUtil.toBean(empMsg, Employee.class);
        Long shopId = employee.getShopId();
        //shopid不能为空
        if (shopId==null){
            return JsonResult.error("账号信息异常，请联系管理员",SYSTEM_LOGIN_ERROR);
        }

        //通过shopid查询店铺信息
        Shop shop = shopService.getById(shopId);
        if (shop==null){
            return JsonResult.error("店铺信息异常，请联系管理员",SYSTEM_LOGIN_ERROR);
        }
        String shopAddress = shop.getAddress();
        Long msgId = msg.getId();
        //查询寻主表
        SearchMasterMsg searchMasterMsg = this.getById(msgId);


        if (!DistanceUtil.isInCircle(searchMasterMsg.getAddress(), shopAddress,5000)) {
            return JsonResult.error("距离超过5000米！");
        }

        //设置状态
        searchMasterMsg.setState(SEARCH_MSG_PASS);
        searchMasterMsg.setShopId(shopId);
        this.updateById(searchMasterMsg);
        return JsonResult.success("接单成功");
    }
}
